package util;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
@Component
public class SendEmailUtil
{
    @Value("${mail.host}")
    private  String host    ;
    @Value("${mail.port}")
    private  int    port    ;
    @Value("${mail.username}")
    private  String username;
    @Value("${mail.password}")
    private  String password;
    @Value("${mail.from}")
    private  String from    ;

    public void sendEmail(String target, String title, String content) throws Exception
    {
        JavaMailSenderImpl  javaMailSender      =   new JavaMailSenderImpl()            ;
        //设置服务器地址及账号密码
        javaMailSender.setHost(host)                                                    ;
        javaMailSender.setPort(port)                                                    ;
        javaMailSender.setUsername(username)                                            ;
        javaMailSender.setPassword(password)                                            ;
        javaMailSender.setDefaultEncoding("UTF-8")                                      ;
        //创建一个程序与邮件服务器会话对象
        Properties          properties          =   new Properties()                    ;
        properties.put("mail.smtp.auth","true")                                         ;
        properties.put("mail.smtp.timeout","25000")                                     ;
        //服务器SSL加密
        MailSSLSocketFactory SSLSocketFactory   =   new MailSSLSocketFactory()          ;
        SSLSocketFactory.setTrustAllHosts(true)                                         ;
        properties.put("mail.smtp.ssl.enable","true")                                   ;
        properties.put("mail.smtp.ssl.socketFactory",SSLSocketFactory)                  ;
        //创建邮件消息
        MimeMessage         mimeMessage         =   javaMailSender.createMimeMessage()  ;
        MimeMessageHelper   mimeMessageHelper   =   new MimeMessageHelper(mimeMessage)  ;
        //设置收件人,寄件人
        mimeMessageHelper.setTo(target)                                                 ;
        mimeMessageHelper.setFrom(from)                                                 ;
        mimeMessageHelper.setSubject(title)                                             ;
        mimeMessageHelper.setText(content,true)                                    ;
        //发送邮件
        javaMailSender.setJavaMailProperties(properties)                                ;
        javaMailSender.send(mimeMessage)                                                ;
    }

}
